package com.example.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ObjectBeanUtils {

    // 获取百分比
    public static double percentage(Object obj, List<String> beanlist) {
        int num = 0;
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        Map<String, Object> map = new HashMap<>();
        // 获取属性名称
        if (declaredFields != null && declaredFields.length > 0) {
            for (int i = 0; i < declaredFields.length; i++) {
                // 获取value
                if("id".equals(declaredFields[i].getName())){
                    continue;
                }
                Object value = getFieldValueByName(declaredFields[i].getName(), obj);

                map.put(declaredFields[i].getName(), value);
            }
            // 判断必输项个数
            if (beanlist != null && beanlist.size() > 0) {
                for (String beanName : beanlist) {
                    Object o = map.get(beanName);
                    if (o != null) {
                        num++;
                    }
                }
            }

            //计算百分比
            if (num == 0) {
                return num;
            } else {
                double rate = (double) num / beanlist.size();
                return rate;
            }
        }

        return num;
    }

    // 通过属性获取值
    public static Object getFieldValueByName(String fieldName, Object o) {

        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();

            String getter = "get" + firstLetter + fieldName.substring(1);

            Method method = o.getClass().getMethod(getter, new Class[] {});
            Object value = method.invoke(o, new Object[] {});

            return value;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }




}
